package com.example.beautymakeup.service.impl;

import com.example.beautymakeup.dao.AddressDao;
import com.example.beautymakeup.domain.PageBean;
import com.example.beautymakeup.pojo.Address;
import com.example.beautymakeup.pojo.Hot;
import com.example.beautymakeup.service.AddressService;
import com.example.beautymakeup.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressDao addressDao;

    @Override
    public PageBean<Address> get(String token) throws Exception {
        String subject = JwtUtil.parseJWT(token).getSubject();
        if (!"admin".equals(subject)){
            List<Address> addresses = addressDao.getByUserId(Integer.parseInt(subject));
            int count = addressDao.getCount(Integer.parseInt(subject));
            PageBean<Address> pageBean = new PageBean<>();
            pageBean.setTotalCount(count);
            pageBean.setRows(addresses);
            return pageBean;
        }
        return null;
    }

    @Override
    public boolean update(String token, Address address) throws Exception {
        String subject = JwtUtil.parseJWT(token).getSubject();
        if (!"admin".equals(subject)){
            address.setUserId(Integer.valueOf(subject));
            return addressDao.update(address) == 1;
        }
        return false;
    }

    @Override
    public boolean add(String token, Address address) throws Exception {
        String subject = JwtUtil.parseJWT(token).getSubject();
        if (!"admin".equals(subject)){
            address.setUserId(Integer.valueOf(subject));
            return addressDao.add(address) == 1;
        }
        return false;
    }

    @Override
    public Address getByUid(String token, int uid) throws Exception {
        String subject = JwtUtil.parseJWT(token).getSubject();
        if (!"admin".equals(subject)){
            return addressDao.getByUid(uid);
        }
        return null;
    }

    @Override
    public boolean delete(String token, Address address) throws Exception {
        String subject = JwtUtil.parseJWT(token).getSubject();
        if (!"admin".equals(subject)){
            address.setUserId(Integer.valueOf(subject));
            return addressDao.delete(address) == 1;
        }
        return false;
    }
}
